package com.lingyun.common.utils.ip;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;


/**
 * IP工具类
 *
 * @author 没事别学JAVA
 */
public class IpUtils {

    /**
     * 获取客户端IP
     *
     * @param request 请求对象
     * @return ip地址
     */
    public static String getClientIp(HttpServletRequest request) {

        String ipAddress = request.getHeader("x-forwarded-for");

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Forwarded-For");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Real-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        if (ipAddress.equals("0:0:0:0:0:0:0:1")) {
            // internal IP address(内网IP)
            ipAddress = "127.0.0.1";
        }
        if (ipAddress.startsWith("192.168.") || ipAddress.startsWith("10.") || ipAddress.startsWith("172.16.")) {
            // internal IP address(内网IP)
            return ipAddress;
        } else {
            // public IP address(公网IP)
            return ipAddress;
        }
    }


    /**
     * 获取客户端IP归属地
     *
     * @param ipAddress 客户端IP归属地
     * @return 客户端IP归属地
     */
    public static String getRealAddressByIP(String ipAddress) {

        if (ipAddress.startsWith("192.168.") || ipAddress.startsWith("10.") || ipAddress.startsWith("172.16.")) {
            // 内网IP
            return "内网IP";
        } else if (ipAddress.equals("127.0.0.1")) {
            return "内网IP";
        } else {
            String result = HttpUtil.get("https://dns.aizhan.com" + "/" + ipAddress + "/", CharsetUtil.CHARSET_UTF_8);
            return StringUtils.substringBetween(StringUtils.substringBetween(result, "<i class=\"ico-bg-ydpm\"></i>", "<i class=\"ico-bg-map\"></i>"), "<strong>", "</strong>");
        }

    }


}
